import java.net.*;

public class UdpTest {
    static public void main(String [] args) throws Exception {
        int port = 9183;
        byte [] data = new byte[1024];
        DatagramPacket packet = new DatagramPacket(data, data.length);
        String s = null;

        if (args.length == 0) {
            DatagramSocket sd = new DatagramSocket(null);
            sd.setReuseAddress(true);
            sd.bind(new InetSocketAddress(port));

            while (true) {
                sd.receive(packet);
                s = new String(packet.getData(), 0, packet.getLength());
                System.out.printf("%s: %s\n", packet.getSocketAddress(), s);
                if (s.equals("quit"))
                    break;
            }
            sd.close();

        } else {
            DatagramSocket sd = new DatagramSocket();
            if (sd.getBroadcast()) {
                System.out.printf("套接字启动了广播!\n");
            } else {
                sd.setBroadcast(true);
            }
            packet.setSocketAddress(new InetSocketAddress("192.168.1.255", port));
            packet.setData(args[0].getBytes());
            sd.send(packet);
            sd.close();
        }
    }
}
